<?php
namespace app\hotback\controller;
use app\admin\logic\ZzLogic;
use think\Db;
use app\service\MoneyCashService;
use think\Request;

class Moneycash extends Base
{
	public function _initialize()
	{
		// 调用父类前置方法
		parent::_initialize();

		// 登录校验
		$this->IsLogin();
	}

	public function index()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			if(!empty($params['page']) && !empty($params['limit']))
			{
				$map = [];
				$map['status2']=1;
				if(isset($params['status']) && $params['status'] != '')
				{
					$map['status'] = $params['status'];
				}
                if(isset($params['bank_username']) && $params['bank_username'] != '')
                {
                    $map['bank_username'] = $params['bank_username'];
                }

                if (!empty($params['city'])){
                    $ap = $map;
                    $ap['t.city'] = $params['city'];
                }else{
                    $ap = $map;
                }
                if (!empty($params['expire_start_time']))
                    $map['add_time'] = ['>=', strtotime($params['expire_start_time'])];
                if (!empty($params['expire_end_time']))
                    $map['add_time'] = ['<', strtotime($params['expire_end_time'])];
                if (!empty($params['expire_end_time']) && !empty($params['expire_start_time']))
                    $map['add_time'] = ['between', strtotime($params['expire_start_time']).','.strtotime($params['expire_end_time'])];

				$count = Db::name('money_cash')->where($map)->count();
				$list_data = Db::name('money_cash')
                    ->alias('c')
                    ->join('techn t','c.identity_id = t.id')
                    ->where('c.identity_type','techn')
                    ->where($ap)
                    ->limit(($params['page']-1)*$params['limit'],$params['limit'])
                    ->field('c.*,t.city')
                    ->order('c.id desc')
                    ->select();


//                echo(Db::name('money_cash')->getLastSql());die;

				$all_money = Db::name('money_cash')->where($map)->sum('money');
				if(!empty($list_data))
				{
					//打款状态
					$status_array = MoneyCashService::$status_array;
					//遍历处理
					foreach($list_data as $key => $value)
					{
						//审核url
						$list_data[$key]['audit_url'] = url('Moneycash/auditinfo', ['id' => $value['id']]);
					    
					    //提现申请时间
					    $list_data[$key]['add_time_time'] = !empty($value['add_time']) ? date('Y-m-d H:i:s', $value['add_time']) : '';
					    $list_data[$key]['zong_time_time'] = !empty($value['zong_time']) ? date('Y-m-d H:i:s', $value['zong_time']) : date('Y-m-d H:i:s', $value['upd_time']);

					    //打款状态
					    $list_data[$key]['status_name'] = !empty($status_array[$value['status']]['name']) ? $status_array[$value['status']]['name'] : '';

                        //所属城市
                        $list_data[$key]['city_name'] = Db::name('proxy')->where('proxy_id',$value['form_proxy_id'])->where('is_delete_time',0)->value('company_name');

					}
					$result['code'] = 0;
	        		$result['msg'] = "请求成功";
	        		$result['data'] = $list_data;
	        		$result['data']['all_money'] = $all_money;
	        		$result['count'] = $count;
				}else
				{
					$result['code'] = -1;
	        		$result['msg'] = "暂无数据";
				}
			}
			echo json_encode($result);
		}else
		{
			//打款状态
			$status_array = MoneyCashService::$status_array;
            $all = Db::name('money_cash')
                ->where('status',0)
                ->where('status2',1)
                ->where('identity_type','techn')
                ->sum('money');

            $city = Db::name('proxy')->where('is_delete_time',0)->field('company_name,shi')->select();
			$this->assign('city', $city);
			$this->assign('status_array', $status_array);
			$this->assign('all', $all);
			return $this->fetch();
		}
	}

	/**
	 * 提现审核页面 
	 */
	public function auditinfo()
	{
		// 参数
		$params = input();
		if(!empty($params['id']))
		{
			//查询
			$info = Db::name('money_cash')->where(['id' => $params['id']])->find();
			if(!empty($info))
			{
				$this->assign('info',$info);
				return $this->fetch();
			}
		}else
		{
			return "缺少参数";
		}
	}

	public function audit()
	{
		$result['code'] = -1;
		$result['msg'] = '非法请求';
		if(request()->isPost())
		{
			$params = input();
			$validate = $this->validate(
				$params,
				[
					'id' => 'require',
					'status' => 'require'
				],
				[
					'id.require' => '提现id有误',
					'status.require' => '请选择审核状态'
				]
			);
			if(true !== $validate){
				echo json_encode(['code' => -1, 'msg' => $validate]);
				exit();
			}
			// 获取提现数据
			$info = Db::name('money_cash')->where(['id' => $params['id']])->find();
			if(empty($info))
			{
				echo json_encode(['code' => -10, 'msg' => '提现数据不存在或已删除']);
				exit();
			}
			// 状态
			if($info['status'] == 1)
			{
				echo json_encode(['code' => -11, 'msg' => '状态不可操作']);
				exit();
			}
			//身份类型对应的数据表
			$identity_table = '';
			switch ($info['identity_type']) {
				case 'techn':
					$identity_table = 'techn';
				break;
			}
			//判断身份类型获取对应的身份信息
			$identity_info = Db::name($identity_table)->where(['id' => $info['identity_id']])->find();
			if(empty($identity_info))
			{
				echo json_encode(['code' => -12, 'msg' => '用户不存在']);
				exit();
			}
			// 数据处理
			if($params['status'] == 1)
			{
				//同意
				//更新对应身份余额
				$iy_upd_data = [
					'lock_money' => PriceNumberFormat($identity_info['lock_money'] - $info['money'])
				];
				// 提现更新数据
				$cash_upd_data = [
        			'status' => 1,
        			'pay_money' => $info['money'],
        			'pay_time' => time(),
        		];

        		//日志
        		$money_log_data = [
        			[
        				'identity_type' => $info['identity_type'],
	            		'identity_id' => $info['identity_id'],
        				'business_type' => 6,
        				'money_type' => 1,
        				'operation_type' => 0,
        				'operation_money' => $info['money'],
        				'original_money' => $identity_info['lock_money'],
        				'latest_money' => $iy_upd_data['lock_money'],
        				'msg' => '管理员审核 [ 提现申请成功，冻结金额减少'.$info['money'].'元]',
        				'add_time' => time()
        			]
        		];
                //提现操作
                $result = ZzLogic::techn_zfb($info['money'],$info['bank_accounts'],$info['bank_username']);
                if ($result['code'] == 0){
                    $insert_info['techn_id'] = $info['identity_id'];
                    $insert_info['cash_id'] = $info['id'];
                    $insert_info['out_biz_no'] = $result['out_biz_no'];
                    $insert_info['status'] = 1;
                    $insert_info['add_time'] = time();
                    $insert_info['bank_accounts'] = $info['bank_accounts'];
                    $insert_info['bank_username'] = $info['bank_username'];
//                    $insert_info['zong_time'] = time();
                    Db::name('techn_zzf')->insert($insert_info);
                }else{
                    $insert_info['techn_id'] = $info['identity_id'];
                    $insert_info['cash_id'] = $info['id'];
                    $insert_info['status'] = 0;
                    $insert_info['add_time'] = time();
                    $insert_info['bank_accounts'] = $info['bank_accounts'];
                    $insert_info['bank_username'] = $info['bank_username'];
//                    $insert_info['zong_time'] = time();
                    $insert_info['msg'] = $result['msg'];
                    Db::name('techn_zzf')->insert($insert_info);
                    //更改提现申请状态
                    Db::name('money_cash')->where('id',$info['id'])->update(['status'=>3]);
                    echo json_encode(['code' => -101, 'msg' => $result['msg']]);
                    exit();
                }

			}else
			{
				//拒绝
        		//更新对应身份余额
        		$iy_upd_data = [
        			'lock_money' => PriceNumberFormat($identity_info['lock_money'] - $info['money']),
        			'money' => PriceNumberFormat($identity_info['money'] + $info['money'])
        		];

        		// 提现更新数据
        		$cash_upd_data = [
        			'status' => 2
        		];

        		//日志
        		$money_log_data = [
        			[
        				'identity_type' => $info['identity_type'],
	            		'identity_id' => $info['identity_id'],
        				'business_type' => 6,
        				'money_type' => 1,
        				'operation_type' => 0,
        				'operation_money' => $info['money'],
        				'original_money' => $identity_info['lock_money'],
        				'latest_money' => $iy_upd_data['lock_money'],
        				'msg' => '管理员审核 [ 提现申请失败，冻结金额释放'.$info['money'].'元]',
        				'add_time' => time()
        			],
        			[
        				'identity_type' => $info['identity_type'],
	            		'identity_id' => $info['identity_id'],
        				'business_type' => 6,
        				'money_type' => 0,
        				'operation_type' => 1,
        				'operation_money' => $info['money'],
        				'original_money' => $identity_info['money'],
        				'latest_money' => $iy_upd_data['money'],
        				'msg' => '管理员审核 [ 提现申请失败，冻结金额退回至有效金额'.$info['money'].'元]',
        				'add_time' => time()
        			]
        		];
			}
			// 提现更新
			$cash_upd_data['msg'] = empty($params['msg']) ? '' : $params['msg'];
			$cash_upd_data['upd_time'] = time();
			$cash_upd_data['zong_time'] = time();
			// 开始处理
        	Db::startTrans();
        	if(!Db::name('money_cash')->where(['id' => $info['id']])->update($cash_upd_data))
        	{
        		Db::rollback();
        		echo json_encode(['code' => -100, 'msg' => '提现申请操作失败']);
				exit();
        	}

        	// 对应身份余额更新
        	if(!Db::name($identity_table)->where(['id' => $identity_info['id']])->update($iy_upd_data))
        	{
        		Db::rollback();
        		echo json_encode(['code' => -101, 'msg' => '余额操作失败']);
				exit();
        	}
        	// 添加余额日志
        	$money_log_data_count = Db::name('money_log')->insertAll($money_log_data);
        	if($money_log_data_count < count($money_log_data))
			{
				//事务回滚
				Db::rollback();
				echo json_encode(['code' => -101, 'msg' => '日志添加失败']);
				exit();
			}



			// 处理成功
        	Db::commit();


        	echo json_encode(['code' => 0, 'msg' => '操作成功']);
		}
	}
    public function zz_log(Request $request){

        if ($request->isAjax()){

            $param = $request->param();
            if (!empty($param['city'])){
                $map['t.city'] = $param['city'];
                $map['z.techn_id'] = ['>',0];

            }else{
                $map['z.techn_id'] = ['>',0];
            }
            $count = Db::name('techn_zzf')->where('techn_id','>',0)->count();
            $where = $request->param();
            $list = Db::name('techn_zzf')
                ->alias('z')
                ->join('techn t','z.techn_id = t.id')
                ->order('z.id desc')
                ->where('z.techn_id','>',0)
                ->where($map)
                ->field('z.*,t.city')
                ->page($where['page'])
                ->limit($where['limit'])
                ->select();
            $log_status = MoneyCashService::$log_status;
            if (!empty($list)){
                foreach ($list as $key=>$value){
                    $list[$key]['zz_status'] = $log_status[$value['status']]['name'];
                    $list[$key]['add_time_time'] = date('Y-m-d H:i',$value['add_time']);
                    $list[$key]['money'] = Db::name('money_cash')->where('id',$value['cash_id'])->value('money');

                }
                echo json_encode(['code'=>0,'msg'=>'请求成功','data'=>$list,'count'=>$count]);
                die;
            }
        }

        $city = Db::name('proxy')->where('is_delete_time',0)->field('company_name,shi')->select();
        $this->assign('city', $city);
        return $this->fetch();

    }
}